import os
import subprocess
import time

import pywifi
from pywifi import const

from config.config import WifiConfig
from utils.logUtils import log_util

# 设置wifi断开/连接超时时间 单位：秒
WIFI_TIMEOUT = WifiConfig.WIFI_TIMEOUT
# 设置每次检查间隔时间
WIFI_INTERVAL = WifiConfig.WIFI_INTERVAL
# 设置联网超时时间
INTERNET_TIMEOUT = WifiConfig.INTERNET_TIMEOUT
# 默认wifi密码
WIFI_PASSWORD = WifiConfig.WIFI_PASSWORD


class Wifi:
    def __init__(self):
        self.wifi = pywifi.PyWiFi()  # 创建一个无线对象
        self.iface = self.wifi.interfaces()[0]  # 取第一个无线网卡

        self.profile = pywifi.Profile()  # 创建wifi配置对象
        self.profile.auth = const.AUTH_ALG_OPEN  # 网卡的开放
        self.profile.akm.append(const.AKM_TYPE_WPA2PSK)  # wifi加密算法
        self.profile.cipher = const.CIPHER_TYPE_CCMP  # 加密单元

    def disconnect(self):
        """
        断开wifi连接
        :return: 是否断开成功
        """
        self.iface.disconnect()  # 断开连接
        # 等待状态改变
        s = time.time()
        while time.time() - s < WIFI_TIMEOUT:
            if self.iface.status() in [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]:
                return True
            time.sleep(WIFI_INTERVAL)
        return False

    def connect(self, ssid, password):
        """
        连接wifi
        :param ssid: wifi名称
        :param password: wifi密码
        :return: 是否连接成功
        """
        # 设置wifi名称/密码
        self.profile.ssid = ssid
        self.profile.key = password

        # self.iface.remove_all_network_profiles()  # 删除所有的wifi配置
        # Find and remove the profile for the network we want to connect to
        for profile in self.iface.network_profiles():
            if profile.ssid == ssid:
                self.iface.remove_network_profile(profile)
                break

        tmp_profile = self.iface.add_network_profile(self.profile)  # 加载配置文件

        self.iface.connect(tmp_profile)  # 连接wifi

        # 等待连接
        s = time.time()
        while time.time() - s < WIFI_TIMEOUT:
            if self.iface.status() == const.IFACE_CONNECTED:
                return True
            time.sleep(WIFI_INTERVAL)
        return False

    # 查看当前连接的wifi信息
    def get_current_wifi(self):
        """
        获取当前连接的wifi信息
        :return: 当前连接的wifi名称
        """
        if self.iface.status() == const.IFACE_CONNECTED:
            # 执行netsh命令获取WiFi接口信息
            result = subprocess.run(['netsh', 'wlan', 'show', 'interfaces'], capture_output=True)
            # 使用GBK编码解码命令输出
            output = result.stdout.decode('gbk')

            # 对命令输出进行解析，查找SSID
            for line in output.split('\n'):
                if "SSID" in line:
                    # 提取SSID值
                    ssid = line.split(":")[1].strip()
                    return ssid
        return None

    def switch_wifi(self, ssid, password=WIFI_PASSWORD):
        """
        切换wifi
        :param ssid: wifi名称
        :param password: wifi密码 默认为配置文件中的密码
        :return: 是否切换成功
        """
        if self.get_current_wifi() == ssid:
            return True

        if self.disconnect():
            log_util.tk_log(f"切换wifi:{ssid}中...;请确保Wifi密码为{WIFI_PASSWORD}")
            return self.connect(ssid, password)

        return False

    @staticmethod
    def is_internet():
        """
        通过ping百度的方式，判断是否可以联网
        :return: 是否可以联网
        """
        # with open(os.devnull, 'w') as devnull:
        #     result = subprocess.call(['ping', 'www.baidu.com', '-n', '1', '-w', str(INTERNET_TIMEOUT * 1000)], stdout=devnull, stderr=devnull)
        # return result == 0

        s = time.time()
        while time.time() - s < INTERNET_TIMEOUT:
            with open(os.devnull, 'w') as devnull:
                result = subprocess.call(['ping', 'www.baidu.com', '-n', '1'], stdout=devnull, stderr=devnull)
                if result == 0: return True
            time.sleep(WIFI_INTERVAL)
        return False

        # return os.system(f'ping www.baidu.com -n 1 -w {INTERNET_TIMEOUT * 1000}') == 0


if __name__ == "__main__":
    wifi = Wifi()
    wifi.get_current_wifi()
    wifi.switch_wifi("Aoung1", "123456789")
    print(wifi.is_internet())
    time.sleep(5)
    wifi.switch_wifi("Aoung2", "123456789")
    print(wifi.is_internet())
